import { FC, useEffect, useState } from "react"
import { View, TouchableOpacity, Dimensions, ScrollView } from "react-native"
import { ViewStyle, TextStyle, ImageStyle } from "react-native"
import LinearGradient from "react-native-linear-gradient"

import { AutoExpoImage, Text } from "@/components"
import { translate, TxKeyPath } from "@/i18n"
import { Product } from "@/models/Order"
import { useAppTheme } from "@/theme/context"

// Styles

// 工具函数：安全地解析价格字符串
const parsePriceString = (priceStr: string | undefined): number => {
  if (!priceStr) return 0

  try {
    // 移除货币符号和其他非数字字符，保留数字、小数点和负号
    const numericStr = priceStr.replace(/[^\d.-]/g, "")
    const parsed = parseFloat(numericStr)

    // 如果解析失败，尝试处理一些特殊情况
    if (isNaN(parsed)) {
      // 尝试处理包含逗号分隔符的价格（如 "1,300"）
      const commaRemoved = priceStr.replace(/,/g, "")
      const commaParsed = parseFloat(commaRemoved.replace(/[^\d.-]/g, ""))
      if (!isNaN(commaParsed)) {
        return commaParsed
      }

      // 尝试处理纯数字字符串
      const numberOnly = priceStr.replace(/[^\d]/g, "")
      const numberParsed = parseFloat(numberOnly)
      if (!isNaN(numberParsed)) {
        return numberParsed
      }
    }

    return isNaN(parsed) ? 0 : parsed
  } catch {
    return 0
  }
}

// 工具函数：计算原价
const calculateOriginalPrice = (
  localizedPrice: string | undefined,
  times: number | undefined,
  fallbackPrice?: number,
): string => {
  console.log("=== 原价计算调试 ===")
  console.log("输入参数:", { localizedPrice, times, fallbackPrice })

  const price = parsePriceString(localizedPrice)
  const multiplier = times || 1

  console.log("解析后的价格:", price, "倍数:", multiplier)

  // 如果解析失败，尝试使用fallbackPrice（通常是服务器返回的price字段）
  let finalPrice = price
  if (isNaN(price) && fallbackPrice && !isNaN(fallbackPrice)) {
    finalPrice = fallbackPrice
    console.log("Using fallback price:", fallbackPrice)
  }

  if (isNaN(finalPrice) || isNaN(multiplier)) {
    console.warn("Invalid price calculation:", { localizedPrice, times, fallbackPrice })
    return "999"
  }

  const result = (finalPrice * multiplier).toFixed(0)
  console.log("最终计算结果:", result)
  return result
}

interface Props {
  orderData?: any
  coinProducts: Product[]
  payAction: (item: Product, options?: { gift?: boolean; quantity?: number }) => void
}

const RechargeContent: FC<Props> = ({ orderData = {}, coinProducts, payAction }) => {
  const { theme } = useAppTheme()
  const { width } = Dimensions.get("window")
  const [products, setProducts] = useState<(Product & { once?: boolean })[]>([])
  const [onceProduct, setOnceProduct] = useState<(Product & { once?: boolean }) | null>(null)
  const [selectedProduct, setSelectedProduct] = useState<Product | any>(null)

  const getColor = (type: string, once?: boolean) =>
    type === "pro" && !once ? theme.colors.palette.gold200 : theme.colors.text

  const renderContain = (count: number, tx: TxKeyPath | any, color: string, index: number) => {
    if (count) {
      return (
        <View style={$itemDetail} key={index}>
          <View style={$itemDetailCount}>
            <Text size={"xxl"} weight="bold" style={{ color }}>
              {count}
            </Text>
            <Text style={{ color }} tx="common:times" />
          </View>
          {/*<Text size="xs" tx={tx} style={{ color }} />*/}
        </View>
      )
    }
    return <View key={index}></View>
  }

  useEffect(() => {
    const list: (Product & { once?: boolean })[] = []
    let single: (Product & { once?: boolean }) | null = null

    coinProducts?.forEach((p) => {
      let desc: any = {}
      try {
        if (p.tips) {
          const parsed = JSON.parse(p.tips)
          if (parsed && typeof parsed === "object") desc = parsed
        }
      } catch {}

      // 确保 desc 至少有基本结构
      desc = desc || {}

      const item = { ...p, desc } as Product & { once?: boolean }
      const { appleSku } = item
      const type = orderData?.style?.priceLevel

      const isOnceVIP = appleSku === "pixel_bird_once_vip_style" && type === "vip"
      const isOncePro = appleSku === "pixel_bird_once_pro_style" && type === "pro"
      const isVIP = appleSku === "pixel_bird_vip_style" && type !== "pro"
      const isPro = appleSku === "pixel_bird_pro_style"

      if (isOnceVIP || isOncePro || isVIP || isPro) {
        if (appleSku?.startsWith?.("pixel_bird_once_")) {
          item.once = true
          single = item
        }
        // list.push(item)
      }
      list.push(item)
    })

    setProducts(list)
    setOnceProduct(single)
    setSelectedProduct(single || (list.length > 0 ? list[0] : null))
  }, [coinProducts, orderData])

  return (
    <View style={$container}>
      <ScrollView
        style={$containerScrollView}
        contentContainerStyle={$containerScrollContentView}
        showsVerticalScrollIndicator={false}
      >
        {products.map((item, index) => {
          const color = getColor(item.desc?.type ?? "pro", item.once)
          return (
            <TouchableOpacity
              key={index}
              onPress={() => setSelectedProduct(item)}
              activeOpacity={1}
              style={[
                $itemCard,
                item.once && { backgroundColor: theme.colors.palette.gold300 },
                !item.once && item.desc?.type === "pro" && $proTheme,
              ]}
            >
              {item.selectionImage && (
                <AutoExpoImage
                  source={item.selectionImage}
                  maxWidth={width - 20}
                  style={$bgImage}
                />
              )}
              {selectedProduct?.id === item.id && (
                <View
                  style={[
                    $selectedItem,
                    {
                      borderColor: theme.colors.palette.neutral100,
                    },
                  ]}
                />
              )}
              <View style={$itemLeft}>
                <View style={$itemLeftTop}>
                  {/*<AutoExpoImage
                    source={`https://pixelcat-1318686313.cos.ap-shanghai.myqcloud.com/pixel-bird/pb_${
                      item.desc?.type ?? "pro"
                    }_tag.png`}
                    maxHeight={24}
                  />*/}
                  {!item.once && <Text tx="pay:stylePack" style={{ color }} />}
                </View>
                <View style={[$itemLeftContainer, !item.once && $normalTop]}>
                  {item.desc?.contain?.map((count: number, index: number) =>
                    renderContain(
                      count,
                      index === 0 ? "pay:proStyle" : "pay:vipStyle",
                      color,
                      index,
                    ),
                  )}
                </View>
              </View>
              <View style={[$itemRight, item.once && $onceRight]}>
                {item.desc?.times && item.desc?.times > 1 && (
                  <Text size="xxs" style={[$originalPrice, { color, fontSize: 10 }]}>
                    {translate("order:originalPrice")} {item.localizedPriceUnit}
                    {calculateOriginalPrice(item.localizedPrice, item.desc?.times, item.price)}
                  </Text>
                )}
                <View style={$priceRow}>
                  <Text size="sm" style={[$currency, { color }]}>
                    {item.localizedPriceUnit}
                  </Text>
                  <Text font={"alimama"} size="xxl" style={{ color }}>
                    {item.localizedPrice}
                  </Text>
                </View>
              </View>
            </TouchableOpacity>
          )
        })}
      </ScrollView>

      <TouchableOpacity
        onPress={() => payAction(selectedProduct)}
        style={[$itemCard, $onceTitle, $onceBuy]}
        activeOpacity={0.8}
      >
        <LinearGradient
          colors={[theme.colors.palette.neutral600, theme.colors.palette.neutral800]}
          style={$onceBuyBg}
          start={{ x: 0, y: 0 }}
          end={{ x: 0, y: 1 }}
        >
          <Text
            font={"alimama"}
            size="xl"
            weight="bold"
            style={{ color: theme.colors.palette.gold200 }}
          >
            {selectedProduct?.localizedPriceUnit}
            {selectedProduct?.localizedPrice}
            &nbsp;{translate("pay:buyNow")}
          </Text>
        </LinearGradient>
      </TouchableOpacity>
    </View>
  )
}

export default RechargeContent

const $container: ViewStyle = {
  paddingHorizontal: 10,
  paddingVertical: 20,
  minHeight: "100%",
  alignItems: "center",
}

const $itemCard: ViewStyle = {
  flexDirection: "row",
  borderRadius: 18,
  overflow: "hidden",
  marginBottom: 8,
}

const $selectedItem: ViewStyle = {
  position: "absolute",
  top: 0,
  left: 0,
  width: "100%",
  height: "100%",
  borderWidth: 5,
  borderRadius: 18,
}

const $itemLeft: ViewStyle = {
  flex: 0.6,
  paddingLeft: 12,
  paddingTop: 12,
}

const $itemLeftTop: ViewStyle = {
  flexDirection: "row",
  alignItems: "center",
  gap: 12,
}

const $itemLeftContainer: ViewStyle = {
  flexDirection: "row",
  justifyContent: "flex-end",
  gap: 30,
}

const $normalTop: ViewStyle = {
  paddingTop: 30,
}

const $itemDetail: ViewStyle = {
  alignItems: "center",
}

const $itemRight: ViewStyle = {
  flex: 0.4,
  alignItems: "center",
  justifyContent: "center",
  paddingBottom: 20,
  paddingTop: 110,
}

const $onceTitle: ViewStyle = {}

const $proTheme: ViewStyle = {}

const $originalPrice: TextStyle = {
  textDecorationLine: "line-through",
}

const $priceRow: ViewStyle = {
  flexDirection: "row",
  alignItems: "baseline",
}

const $currency: TextStyle = {
  marginRight: 2,
}

const $onceRight: ViewStyle = {
  paddingTop: 80,
}

const $onceBuy: ViewStyle = {
  position: "absolute",
  bottom: 12,
}

const $onceBuyBg: ViewStyle = {
  width: "100%",
  justifyContent: "center",
  alignItems: "center",
  borderRadius: 18,
  height: 72,
}

const $bgImage: ImageStyle = {
  position: "absolute",
  height: "100%",
  top: 0,
  left: 0,
}

const $itemDetailCount: ViewStyle = {
  flexDirection: "row",
  alignItems: "flex-end",
  gap: 4,
}

const $containerScrollView: ViewStyle = { flex: 1, width: "100%" }
const $containerScrollContentView: ViewStyle = { paddingBottom: 120 }
